import Web3 from 'web3';
import { promises as fs } from 'fs';


const erc20Abi = [
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" },
    { "constant": false, "inputs": [{ "name": "spender", "type": "address" }, { "name": "amount", "type": "uint256" }], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "type": "function" },
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }, { "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" }
];

async function main() {
    // 读取合约 ABI
    const jsonData = await fs.readFile('./build/contracts/L1Bridge.json', 'utf-8');
    const bridgeJson = JSON.parse(jsonData);
    const bridgeAbi = bridgeJson.abi;

    // 配置参数
    const BRIDGE_CONTRACT_ADDRESS = '0xe9EF2AAfe1f11cBd3c72E87701047699a12067a7'; // L1Bridge 合约地址

    const OWNER_ADDRESS = '0xa659f022cb8d0Df682C327d2f16B6f2f41AD2aeA'; // 合约所有者地址
    const PRIVATE_KEY = '0x7fd651a63dcca634d0b527bde1b96f1d2ee246af361f03f951723db27e24e54c'; // 合约所有者私钥
    const RPC_URL = 'http://[::1]:8545'; // 以太坊节点 RPC URL
    const TOKEN_CONTRACT_ADDRESS = '0x43F0FFCA27B26dCfA02fce8cA5D97F2F85CbF3fa'; // ERC20 代币合约地址
    const RECIPIENT_ADDRESS = '0xbc8C79C69e40F404DAA9f5CC17Cb35868C262CfD'; // 收款人地址
    const WITHDRAW_AMOUNT = Web3.utils.toWei('9.0', 'ether'); // 提取的代币数量

    // 创建 Web3 实例
    const web3 = new Web3(RPC_URL);

    // 创建钱包签名者
    const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
    web3.eth.accounts.wallet.add(account);
    web3.eth.defaultAccount = account.address;


    console.log('Web3 已成功连接:');

    // 创建 ERC20 代币合约实例
    const tokenContract = new web3.eth.Contract(erc20Abi, TOKEN_CONTRACT_ADDRESS);
    // 获取合约拥有者余额
    const balance = await tokenContract.methods.balanceOf(OWNER_ADDRESS).call();
    console.log(`当前余额: ${web3.utils.fromWei(balance, 'ether')} Tokens`);

    // 检查是否已批准足够的代币给桥合约
    const allowance = await tokenContract.methods.allowance(OWNER_ADDRESS, BRIDGE_CONTRACT_ADDRESS).call();
    if (parseInt(allowance) < parseInt(WITHDRAW_AMOUNT)) {
        console.log("批准代币给桥合约...");
        const approveTx = tokenContract.methods.approve(BRIDGE_CONTRACT_ADDRESS, WITHDRAW_AMOUNT);
        const approveSignedTx = await web3.eth.sendTransaction({
            from: OWNER_ADDRESS,
            to: TOKEN_CONTRACT_ADDRESS,
            data: approveTx.encodeABI(),
            gas: 200000,
        });
        console.log("批准已完成。交易哈希:", approveSignedTx.transactionHash);
    } else {
        console.log("已批准足够的代币给桥合约。");
    }


    // 创建 L1Bridge 合约实例
    const bridgeContract = new web3.eth.Contract(bridgeAbi, BRIDGE_CONTRACT_ADDRESS);

    // try {
    //     const result = await bridgeContract.methods.withdraw(RECIPIENT_ADDRESS, WITHDRAW_AMOUNT).call();
    //     console.log("模拟交易成功:", result);
    // } catch (error) {
    //     console.error("模拟交易失败:", error.message);
    //     console.error("模拟错误详情:", error);
    //     console.error("模拟错误详情:", JSON.stringify(error, null, 2));
    // }

    //const owner = await bridgeContract.methods.owner().call();

    //console.log("Contract owner is:", owner);
    //console.log("Contract owner is:", owner == web3.eth.defaultAccount);

    // 调用 withdraw 函数
    console.log(`合约所有者正在提取 ${web3.utils.fromWei(WITHDRAW_AMOUNT, 'ether')} Tokens 给地址 ${RECIPIENT_ADDRESS}...`);
    const withdrawTx = bridgeContract.methods.withdraw(RECIPIENT_ADDRESS, WITHDRAW_AMOUNT);

    // 签名并发送交易
    try {
        const signedWithdrawTx = await web3.eth.sendTransaction({
            from: web3.eth.defaultAccount,
            to: BRIDGE_CONTRACT_ADDRESS,
            data: withdrawTx.encodeABI(),
            gas: 20000000,
        });
        console.log("提取已完成。交易哈希:", signedWithdrawTx.transactionHash);
    } catch (error) {
        console.error("Error details:", JSON.stringify(error, null, 2));
    }

    // 监听 Withdrawal 事件
    bridgeContract.events.Withdrawal({
        filter: { user: RECIPIENT_ADDRESS },
        fromBlock: 'latest'
    })
    .on('data', (event) => {
        console.log("检测到提取事件:");
        console.log(`收款人地址: ${event.returnValues.user}`);
        console.log(`提取金额: ${web3.utils.fromWei(event.returnValues.amount, 'ether')} Tokens`);
        console.log(`时间戳: ${new Date(Number(event.returnValues.timestamp) * 1000).toLocaleString()}`);
        console.log('-----------------------------');
    });

    console.log("监听 Withdrawal 事件中...");
}

main().catch(error => {
    console.error("发生错误:", error);
    process.exit(1);
});
